import dayjs from 'dayjs'
import { dateFormatPattern, variableExpressPattern } from './pattern'

const DEFAULT_FORMAT = 'YYYY-MM-DD'
const DATETIME_FUNC_NAME = 'datetime()'

class Template {
  public render (str: string, variable?: string) {
    return str.replace(variableExpressPattern, (src, key: string) => {
      if (key.startsWith(DATETIME_FUNC_NAME.slice(0, -1))) {
        const format = key === DATETIME_FUNC_NAME
          ? DEFAULT_FORMAT
          : key.match(dateFormatPattern)?.[1] || DEFAULT_FORMAT

        return dayjs().format(format)
      }
      if (variable) {
        return variable
      }
      return src
    })
  }
}

export const template = new Template()
